<?php

namespace App\Trip\Geo;

use Exception;

class Location
{
    /**
     * @var string
     */
    private string $longitude;
    /**
     * @var string
     */
    private string $latitude;


    public function __construct(string $location)
    {
        [$longitude, $latitude] = $location ? explode(',', urldecode($location)) : ['', ''];
        $this->longitude = $longitude;
        $this->latitude  = $latitude;
    }


    public function getLocation(): array
    {
        return [$this->longitude, $this->latitude];
    }

    /**
     * @throws Exception
     */
    public function getDistance(Location $location): float
    {

        $longitude1 = $this->longitude;
        $latitude1  = $this->latitude;
        $longitude2 = $location->getLongitude();
        $latitude2  = $location->getLatitude();
        $theta      = $longitude1 - $longitude2;
        $dist       = sin(deg2rad($latitude1)) * sin(deg2rad($latitude2)) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta));
        $dist       = acos($dist);
        $dist       = rad2deg($dist);
        $miles      = $dist * 60 * 1.1515;
        return ($miles * 1.609344);
    }

    /**
     * 经度
     * @return string
     */
    public function getLongitude(): string
    {
        return $this->longitude;
    }

    public function getLatitude(): string
    {
        return $this->latitude;
    }

    public function __toString()
    {
        return $this->longitude.','.$this->latitude;
    }


}